package com.example.netty.netty.codec2;

import com.example.netty.netty.codec.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    //通道准备好时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        MyDataInfo.MyMessage student =
                //设置消息类型
                MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType)
                //设置消息内容
                .setStudent(MyDataInfo.Student.newBuilder().setId(2).setName("李四").build()).build();
        ctx.channel().writeAndFlush(student);

        MyDataInfo.MyMessage worker =
                //设置消息类型
                MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType)
                //设置消息内容
                .setWorder(MyDataInfo.Worker.newBuilder().setName("张三").setAge(39).build()).build();
        ctx.channel().writeAndFlush(worker);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //有读取事件时触发
        System.out.println("上下文信息："+ctx);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("接受到信息："+buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址："+ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
